import socket
import threading
import json
import struct
import random
import time

# 添加全局变量用于存储路径导航信息
navigation_path = []  # 存储完整的路径列表
current_path_index = 0  # 当前路径索引
finished_path = []  # 已完成的路径
unfinished_path = []  # 未完成的路径
navigation_timer = None  # 定时器
is_navigating = False  # 导航状态

latest_nick_name = "srd-seer-zll"  # 默认值
navigation_status = 2   # (0 = NONE, 1 = WAITING(目前不可能出现该状态), 2 = RUNNING, 3 = SUSPENDED, 4 = COMPLETED, 5 = FAILED, 6 = CANCELED)

# 处理每个客户端连接的函数
def handle_client(conn, addr, port):
    print(f"[+] 客户端连接来自 {addr[0]}:{addr[1]}，服务端端口 {port}")
    buffer = b""  # 用于存储未处理完的数据
    try:
        while True:
            try:
                data = conn.recv(1024)
                if not data:
                    break  # 如果客户端断开连接，退出循环

                buffer += data  # 将新接收的数据添加到缓冲区

                # 循环处理缓冲区中的完整数据包
                while len(buffer) >= 16 and buffer[0] == 0x5A:
                    # 解析SeerHeader结构 (总共16字节)
                    header = buffer[:16]
                    try:
                        # 根据C++的SeerHeader结构解析:
                        # uint8_t m_header;
                        # uint8_t m_version;
                        # uint16_t m_number;
                        # uint32_t m_length;
                        # uint16_t m_type;
                        # uint8_t m_reserved[6];
                        m_header, m_version, m_number, m_length, m_type, reserved = struct.unpack('>BBHIH6s', header)
                    except struct.error as e:
                        print(f"[!] 数据包头解析错误: {e}")
                        print(f"数据: {header.hex(' ').upper()}")
                        buffer = buffer[1:]  # 跳过一个字节继续尝试
                        continue

                    # 检查缓冲区中是否有完整的数据包（包括头部和数据）
                    if len(buffer) < 16 + m_length:
                        break  # 数据不完整，等待更多数据

                    # 提取完整数据包
                    packet_data = buffer[:16 + m_length]
                    buffer = buffer[16 + m_length:]  # 剩余数据保留在缓冲区

                    # 处理数据包
                    process_packet(conn, addr, port, packet_data)
            except ConnectionResetError:
                print(f"[!] 连接被客户端 {addr[0]}:{addr[1]} 重置")
                break
            except BrokenPipeError:
                print(f"[!] 客户端 {addr[0]}:{addr[1]} 管道已断开")
                break
            except socket.timeout:
                print(f"[!] 客户端 {addr[0]}:{addr[1]} 连接超时")
                break
            except Exception as e:
                print(f"[!] 接收数据时发生未知错误: {e}")
                break
    except Exception as e:
        print(f"[!] 处理客户端 {addr[0]}:{addr[1]} 时发生错误: {e}")
    finally:
        try:
            conn.close()  # 确保连接最终关闭
            print(f"[-] 客户端连接已关闭 {addr[0]}:{addr[1]}")
        except Exception as e:
            print(f"[!] 关闭连接时发生错误: {e}")

# 添加定时器函数用于更新导航状态
def start_navigation_timer():
    global navigation_timer
    # 如果已有定时器在运行，先取消它
    if navigation_timer:
        navigation_timer.cancel()
    
    # 创建新的定时器，20秒后执行
    navigation_timer = threading.Timer(20.0, update_navigation_status)
    navigation_timer.start()
    print("导航定时器已启动，将在60秒后更新站点信息")

# 更新导航状态的函数
def update_navigation_status():
    global current_path_index, navigation_path, finished_path, unfinished_path
    global is_navigating, navigation_status, navigation_timer
    
    # 更新路径状态
    if is_navigating and navigation_path:
        # 将当前站点移到已完成列表
        if current_path_index < len(navigation_path):
            current_station = navigation_path[current_path_index]
            # 注意：对于往返路径，同一个站点可能会多次出现在finished_path中
            finished_path.append(current_station)
            if current_station in unfinished_path:
                unfinished_path.remove(current_station)
        
        # 移动到下一个站点
        current_path_index += 1
        
        # 检查是否已完成所有路径
        if current_path_index >= len(navigation_path):
            # 导航完成
            is_navigating = False
            navigation_status = 4  # COMPLETED
            print("导航已完成所有站点")
        else:
            # 继续导航
            print(f"更新导航状态: 当前站点 {navigation_path[current_path_index]}")
            # 重新启动定时器
            start_navigation_timer()
    else:
        # 导航已停止
        print("导航已停止，不再更新站点信息")

# 处理单个数据包的函数
def process_packet(conn, addr, port, data):
    global latest_nick_name, navigation_status, navigation_path, current_path_index  # 声明使用全局变量
    global finished_path, unfinished_path, is_navigating

    if len(data) < 16 or data[0] != 0x5A:
        return

    # 解析SeerHeader结构 (总共16字节)
    header = data[:16]
    try:
        # 根据C++的SeerHeader结构解析:
        # uint8_t m_header;
        # uint8_t m_version;
        # uint16_t m_number;
        # uint32_t m_length;
        # uint16_t m_type;
        # uint8_t m_reserved[6];
        m_header, m_version, m_number, m_length, m_type, reserved = struct.unpack('>BBHIH6s', header)
    except struct.error as e:
        print(f"[!] 数据包头解析错误: {e}")
        print(f"数据: {header.hex(' ').upper()}")
        return

    # 打印收到的数据包的16进制表示
    hex_data = data.hex(' ').upper()
    print(f"收到二进制数据包: 来自 {addr[0]}:{addr[1]}")
    print(f"数据包十六进制: {hex_data}")
    print(f"类型: {m_type} (0x{m_type:04X}), 编号: {m_number}, 数据长度: {m_length}")

    # 根据m_type和端口响应
    if port == 19204 and m_type == 0x03EF:  # 0x03EF = 1007
        # 构造响应数据
        response_data = {
            "auto_charge": False,
            "battery_cycle": 0,
            "battery_level": random.uniform(0.0, 1.0),  # 动态变化的电池电量
            "battery_temp": -0.0,
            "battery_user_data": "",
            "charging": False,
            "create_on": "2025-07-17T15:42:50.007-1100",
            "current": -0.0,
            "extra": "",
            "manual_charge": False,
            "max_charge_current": -0.0,
            "max_charge_voltage": -0.0,
            "ret_code": 0,
            "voltage": -0.0
        }

        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型1004的响应处理（查询机器人位置）
    elif port == 19204 and m_type == 0x03EC:  # 0x03EC = 1004
        # 获取当前和上一个站点信息
        current_station = ""
        last_station = ""
        
        if navigation_path and is_navigating:
            if current_path_index < len(navigation_path):
                current_station = navigation_path[current_path_index]
            if current_path_index > 0:
                last_station = navigation_path[current_path_index - 1]
        
        # 构造响应数据，动态生成x和y坐标
        response_data = {
            "angle": 1.6083,
            "confidence": 0.5079,
            "correction_errs": [],
            "create_on": "2025-07-17T15:43:41.168-1100",
            "current_station": current_station,
            "in_forbidden_area": False,
            "last_station": last_station,
            "loc_method": 0,
            "loc_notify": "",
            "loc_state": 1,
            "reliabilities": [],
            "ret_code": 0,
            "similarity": 0,
            "update_reason": 0,
            "x": random.uniform(-10.0, 10.0),  # 动态变化的x坐标
            "y": random.uniform(-10.0, 10.0)   # 动态变化的y坐标
        }

        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型1020的响应处理(查询机器人导航状态)
    elif port == 19204 and m_type == 0x03FC:  # 0x03FC = 1020
        # 获取当前目标站点
        target_id = ""
        if navigation_path and is_navigating and current_path_index < len(navigation_path):
            target_id = navigation_path[current_path_index]
        
        # 构造响应数据，动态生成task_type
        response_data = {
            "task_status": navigation_status,
            "task_type": random.choice([3, 4, 5, 6]),  # 动态变化的task_type
            "target_id": target_id,
            "finished_path": finished_path.copy(),
            "unfinished_path": unfinished_path.copy(),
            "containers": [{
                "container_name": "1",
                "desc": "first good",
                "goods_id": "good1",
                "has_goods": True
            }, {
                "container_name": "2",
                "desc": "",
                "goods_id": "",
                "has_goods": False
            }]
        }

        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型1300的响应处理（查询机器人载入的地图以及储存的地图）
    elif port == 19204 and m_type == 0x0514:  # 0x0514 = 1300
        # 构造响应数据
        response_data = {
            "create_on": "2025-07-17T15:40:00.418-1100",
            "current_map": "20250821113608070",
            "current_map_md5": "fa08c6d355b20b5e1b5691708e97c376",
            "map_files_info": [
                {"modified": "2025-08-21 11:36:08", "name": "20250821113608070.smap", "size": 786740},
                {"modified": "2025-05-06 10:24:28", "name": "20250806102428716.smap", "size": 892392},
                {"modified": "2025-05-16 13:51:41", "name": "20250513165147113.smap", "size": 395744},
                {"modified": "2025-05-16 17:36:46", "name": "20250516173239774.smap", "size": 353440},
                {"modified": "2025-05-22 10:20:21", "name": "20250520161804942.smap", "size": 362868},
                {"modified": "2025-05-22 10:48:38", "name": "20250522104444667newChassis.smap", "size": 582151},
                {"modified": "2025-05-23 10:52:10", "name": "20250522112805422.smap", "size": 519950},
                {"modified": "2025-05-23 10:57:05", "name": "20250523105852301.smap", "size": 479913},
                {"modified": "2025-05-29 10:54:14", "name": "20250529104714576.smap", "size": 518518},
                {"modified": "2025-05-29 17:42:36", "name": "20250529174459634.smap", "size": 610293},
                {"modified": "2025-05-30 16:47:32", "name": "20250530162919430.smap", "size": 1323965},
                {"modified": "2025-06-04 11:15:17", "name": "20250604110902452.smap", "size": 1279560},
                {"modified": "2025-07-02 18:42:32", "name": "20250612115946500.smap", "size": 877577},
                {"modified": "2025-07-03 15:12:42", "name": "20250703151237615.smap", "size": 1661},
                {"modified": "2025-07-03 17:34:30", "name": "20250703173355313.smap", "size": 477121},
                {"modified": "2025-07-03 17:42:30", "name": "20250703174206434.smap", "size": 498415},
                {"modified": "2025-07-03 18:03:39", "name": "20250703180333117.smap", "size": 309819},
                {"modified": "2025-07-03 18:36:52", "name": "20250703183650392.smap", "size": 230491},
                {"modified": "2025-07-04 14:58:35", "name": "20250704145514088.smap", "size": 250763},
                {"modified": "2025-07-04 16:01:20", "name": "20250704153357110.smap", "size": 318018},
                {"modified": "2025-07-08 17:17:37", "name": "20250707144615895.smap", "size": 295896},
                {"modified": "2025-04-27 10:42:30", "name": "default.smap", "size": 15304}
            ],
            "maps": [
                "20250821113608070",
                "20250806102428716",
                "20250513165147113",
                "20250516173239774",
                "20250520161804942",
                "20250522104444667newChassis",
                "20250522112805422",
                "20250523105852301",
                "20250529104714576",
                "20250529174459634",
                "20250530162919430",
                "20250604110902452",
                "20250612115946500",
                "20250703151237615",
                "20250703173355313",
                "20250703174206434",
                "20250703180333117",
                "20250703183650392",
                "20250704145514088",
                "20250704153357110",
                "20250707144615895",
                "default"
            ],
            "ret_code": 0
        }

        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型4011的响应处理
    elif port == 19207 and m_type == 0x0FAB:  # 0x0FAB = 4011
        # 解析JSON数据部分
        if len(data) > 16 and m_length > 0:
            json_data = data[16:16 + m_length]
            try:
                request_json = json.loads(json_data.decode('utf-8'))
                map_name = request_json.get("map_name", "")
                print(f"解析到的map_name: {map_name}")
                if map_name:
                    # 查找对应的.smap文件
                    response_data = load_smap_file(map_name)
                    if response_data:
                        send_response(conn, addr, m_number, m_type, response_data)
                    else:
                        # 如果找不到文件，发送错误响应
                        error_response = {"ret_code": 1, "error": "Map file not found"}
                        send_response(conn, addr, m_number, m_type, error_response)
                else:
                    # 如果没有map_name字段，发送错误响应
                    error_response = {"ret_code": 2, "error": "Missing map_name field"}
                    send_response(conn, addr, m_number, m_type, error_response)
            except json.JSONDecodeError as e:
                # JSON解析错误，发送错误响应
                print(f"[!] JSON解析错误: {e}")
                error_response = {"ret_code": 3, "error": "Invalid JSON format"}
                send_response(conn, addr, m_number, m_type, error_response)

    # 添加对类型1301的响应处理（查询机器人当前载入地图中的站点信息）
    elif port == 19204 and m_type == 0x0515:  # 0x0515 = 1301
        # 构造响应数据
        response_data = {
            "create_on": "2025-09-18T15:49:08.459-1100",
            "ret_code": 0,
            "stations": [
                {"desc":"lobe_1","id":"LM1","r":-0.0,"spin":"false","type":"LocationMark","x":-3.735,"y":-4.87},
                {"desc":"","id":"LM2","r":-0.0,"spin":"false","type":"LocationMark","x":-0.722,"y":-4.87},
                {"desc":"lobe_1","id":"LM3","r":-0.0,"spin":"false","type":"LocationMark","x":1.744,"y":-4.87},
                {"desc":"lobe_2","id":"LM4","r":-0.0,"spin":"false","type":"LocationMark","x":5.433,"y":-4.87},
                {"desc":"","id":"LM5","r":-0.0,"spin":"false","type":"LocationMark","x":9.482,"y":-4.87},
                {"desc":"lobe_2","id":"LM6","r":-0.0,"spin":"false","type":"LocationMark","x":0.115,"y":0.358},
                {"desc":"","id":"LM7","r":-0.0,"spin":"false","type":"LocationMark","x":12.309,"y":0.358},
                {"desc":"","id":"LM8","r":-0.0,"spin":"false","type":"LocationMark","x":12.309,"y":-4.87}
            ]
        }
        send_response(conn, addr, m_number, m_type, response_data)

    elif port == 19210 and m_type == 0x1774:  # 0x1774 = 6004
        # 解析JSON数据部分
        if len(data) > 16 and m_length > 0:
            json_data = data[16:16 + m_length]
            try:
                request_json = json.loads(json_data.decode('utf-8'))
                status = request_json.get("status", False)
                print(f"解析到的status: {status}")
                # 构造响应数据
                response_data = {
                    "ret_code": 0
                }
                send_response(conn, addr, m_number, m_type, response_data)
            except json.JSONDecodeError as e:
                # JSON解析错误，发送错误响应
                print(f"[!] JSON解析错误: {e}")
                error_response = {"ret_code": 3, "error": "Invalid JSON format"}
                send_response(conn, addr, m_number, m_type, error_response)

    # 添加对类型1060的响应处理
    elif port == 19204 and m_type == 0x0424:  # 0x0424 = 1060
        # 构造响应数据，使用最新的nick_name
        response_data = {
            "create_on": "22:04.194-1100",
            "desc": "",
            "ip": "192.168.1.101",
            "locked": True,
            "nick_name": latest_nick_name,  # 使用保存的nick_name
            "port": 57253,
            "ret_code": 0,
            "time_t": 1755825684,
            "type": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型1303的响应处理（查询任意两点之间的线路）
    elif port == 19204 and m_type == 0x0517:  # 0x0517 = 1303
        # 构造响应数据
        response_data = {
            "create_on": "2025-10-10T18:12:05.305-0700",
            "list": ["LM1", "LM2", "LM3", "LM4", "LM5", "LM6", "LM7", "LM8"],
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型3055的响应处理
    # 添加对类型4005的响应处理
    elif port == 19207 and m_type == 0x0FA5:  # 0x0FA5 = 4005
        # 解析JSON数据部分
        if len(data) > 16 and m_length > 0:
            json_data = data[16:16 + m_length]
            try:
                request_json = json.loads(json_data.decode('utf-8'))
                nick_name = request_json.get("nick_name", "")
                print(f"解析到的nick_name: {nick_name}")
                # 保存nick_name供后续使用
                if nick_name:
                    latest_nick_name = nick_name
                # 构造响应数据
                response_data = {
                    "ret_code": 0
                }
                send_response(conn, addr, m_number, m_type, response_data)
            except json.JSONDecodeError as e:
                # JSON解析错误，发送错误响应
                print(f"[!] JSON解析错误: {e}")
                error_response = {"ret_code": 3, "error": "Invalid JSON format"}
                send_response(conn, addr, m_number, m_type, error_response)

    # 添加对类型4006的响应处理
    elif port == 19207 and m_type == 0x0FA6:  # 0x0FA6 = 4006
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型3055的响应处理
    elif port == 19206 and m_type == 0x0BF3:  # 0x0BF3 = 3055
        # 解析JSON数据部分
        if len(data) > 16 and m_length > 0:
            json_data = data[16:16 + m_length]
            try:
                request_json = json.loads(json_data.decode('utf-8'))
                dist = request_json.get("dist", 0)
                vx = request_json.get("vx", 0)
                vy = request_json.get("vy", 0)
                mode = request_json.get("mode", 0)
                print(f"解析到的参数: dist={dist}, vx={vx}, vy={vy}, mode={mode}")
                # 构造响应数据
                response_data = {
                    "ret_code": 0
                }
                send_response(conn, addr, m_number, m_type, response_data)
            except json.JSONDecodeError as e:
                # JSON解析错误，发送错误响应
                print(f"[!] JSON解析错误: {e}")
                error_response = {"ret_code": 3, "error": "Invalid JSON format"}
                send_response(conn, addr, m_number, m_type, error_response)

    # 添加对类型3056的响应处理
    elif port == 19206 and m_type == 0x0BF4:  # 0x0BF4 = 3056
        # 解析JSON数据部分
        if len(data) > 16 and m_length > 0:
            json_data = data[16:16 + m_length]
            try:
                request_json = json.loads(json_data.decode('utf-8'))
                angle = request_json.get("angle", 0)
                vw = request_json.get("vw", 0)
                mode = request_json.get("mode", 0)
                print(f"解析到的参数: angle={angle}, vw={vw}, mode={mode}")
                # 构造响应数据
                response_data = {
                    "ret_code": 0
                }
                send_response(conn, addr, m_number, m_type, response_data)
            except json.JSONDecodeError as e:
                # JSON解析错误，发送错误响应
                print(f"[!] JSON解析错误: {e}")
                error_response = {"ret_code": 3, "error": "Invalid JSON format"}
                send_response(conn, addr, m_number, m_type, error_response)

    # 添加对类型2002的响应处理（重定位）
    elif port == 19205 and m_type == 0x07D2:  # 0x07D2 = 2002
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型3066的响应处理（指定路径导航）
    elif port == 19206 and m_type == 0x0BFA:  # 0x0BFA = 3066
        # 解析JSON数据部分
        if len(data) > 16 and m_length > 0:
            json_data = data[16:16 + m_length]
            try:
                request_json = json.loads(json_data.decode('utf-8'))
                print(f"收到指定路径导航请求: {request_json}")
                
                # 提取路径列表
                if "move_task_list" in request_json:
                    move_task_list = request_json["move_task_list"]
                    # 从move_task_list中正确提取路径站点
                    navigation_path = []
                    if move_task_list:
                        # 添加第一个任务的起点
                        if "source_id" in move_task_list[0]:
                            navigation_path.append(move_task_list[0]["source_id"])
                        
                        # 依次添加每个任务的终点
                        for task in move_task_list:
                            if "id" in task:
                                navigation_path.append(task["id"])
                    
                    print(f"提取的导航路径: {navigation_path}")
                    
                    # 初始化路径状态
                    if navigation_path:
                        current_path_index = 0
                        finished_path = []
                        unfinished_path = navigation_path.copy()
                        is_navigating = True
                        navigation_status = 2  # 运行状态
                        
                        # 启动定时器，每分钟更新一次站点信息
                        start_navigation_timer()
                
            except json.JSONDecodeError as e:
                print(f"[!] JSON解析错误: {e}")
        
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型3001的响应处理（指定路径导航:暂停导航）
    elif port == 19206 and m_type == 0x0BB9:  # 0x0BB9 = 3001
        navigation_status = 3  # 暂停导航
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型3001的响应处理（指定路径导航:继续导航）
    elif port == 19206 and m_type == 0x0BBA:  # 0x0BBA = 3002
        navigation_status = 2  # 继续导航
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)
    
    # 添加对类型3001的响应处理（指定路径导航:取消导航）
    elif port == 19206 and m_type == 0x0BBB:  # 0x0BBB = 3003
        navigation_status = 6  # 取消导航
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 添加对类型1050的响应处理
    elif port == 19204 and m_type == 0x041A:  # 0x041A = 1050
        # 构造响应数据
        response_data = {
            "create_on": "2023-10-16T14:08:04.869+0800",
            "errors": [
                {
                    "52900": 1697435489,
                    "desc": "[2023-10-16T13:51:29.803+0800] third-party error: from aaaaaaaa",
                    "describe": "third-party error",
                    "method": "",
                    "reason": "",
                    "times": 12
                }
            ],
            "fatals": [],
            "notices": [],
            "ret_code": 0,
            "warnings": [
                {
                    "54900": 1697436477,
                    "desc": "[2023-10-16T14:07:57.753+0800] third-party warning: from 3rd warnings",
                    "describe": "third-party warning",
                    "method": "",
                    "reason": "",
                    "times": 4
                }
            ]
        }
        send_response(conn, addr, m_number, m_type, response_data)
    
        # 自定义子任务START开始响应处理
    elif port == 19303 and m_type == 0x1B5B:  # 0x1B5B = 7003
        # 解析JSON数据部分
        if len(data) > 16 and m_length > 0:
            json_data = data[16:16 + m_length]
            try:
                request_json = json.loads(json_data.decode('utf-8'))
                print(f"收到任务开始请求，解析到的JSON数据:")
                
                # 打印lobe_definition
                if "lobe_definition" in request_json:
                    print(f"  lobe_definition: {request_json['lobe_definition']}")
                
                # 打印其他字段
                path = request_json.get("path", "")
                task_start_location = request_json.get("task_start_location", "")
                task_end_location = request_json.get("task_end_location", "")
                
                print(f"  path: {path}")
                print(f"  task_start_location: {task_start_location}")
                print(f"  task_end_location: {task_end_location}")
                
            except json.JSONDecodeError as e:
                # JSON解析错误
                print(f"[!] JSON解析错误: {e}")
        
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 自定义子任务END结束响应处理
    elif port == 19303 and m_type == 0x1B5C:  # 0x1B5C = 7004
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)

    # 自定义子任务状态响应处理
    elif port == 19303 and m_type == 0x1B5D:  # 0x1B5D = 7005
        
        # 解析JSON数据部分
        if len(data) > 16 and m_length > 0:
            json_data = data[16:16 + m_length]
            try:
                request_json = json.loads(json_data.decode('utf-8'))
                current_location = request_json.get("current_location", "")
                target_location = request_json.get("target_location", "")
                print(f"解析到的位置信息: current_location={current_location}, target_location={target_location}")
            except json.JSONDecodeError as e:
                # JSON解析错误
                print(f"[!] JSON解析错误: {e}")
        
        # 构造响应数据
        response_data = {
            "ret_code": 0
        }
        send_response(conn, addr, m_number, m_type, response_data)
# 发送响应数据的通用函数
def send_response(conn, addr, m_number, m_type, response_data):
    try:
        json_str = json.dumps(response_data, separators=(',', ':'))
        json_bytes = json_str.encode('utf-8')

        # 响应类型为请求类型+10000(0x2710)
        response_type = m_type + 0x2710

        # 构造响应头 (16字节)
        json_size = len(json_bytes)
        m_length = json_size

        # 构造reserved字段，其中包含json_size
        reserved = bytearray(6)
        # 使用4个字节来存储json_size，支持更大的文件
        reserved[0] = (json_size >> 24) & 0xFF  # 最高字节
        reserved[1] = (json_size >> 16) & 0xFF
        reserved[2] = (json_size >> 8) & 0xFF
        reserved[3] = json_size & 0xFF         # 最低字节

        # 打包响应头，保持与请求头一致的格式
        response_header = struct.pack('>BBHIH6s',
                                    0x5A,           # m_header (1字节)
                                    0x01,           # m_version (1字节)
                                    m_number,       # m_number (2字节)
                                    m_length,       # m_length (4字节)
                                    response_type,  # m_type (2字节)
                                    bytes(reserved) # m_reserved (6字节)
                                    )

        # 组合完整响应数据包
        response_packet = response_header + json_bytes

        # 打印发送的响应数据包的16进制表示
        response_hex = response_packet.hex(' ').upper()
        print(f"发送响应数据包到 {addr[0]}:{addr[1]}")
        print(f"响应包大小: {len(response_packet)} 字节")
        print(f"响应包十六进制(前64字节): {response_hex[:192]}{'...' if len(response_hex) > 192 else ''}")

        # 发送数据，增加错误处理
        conn.sendall(response_packet)
        print(f"成功发送响应数据包到 {addr[0]}:{addr[1]}")

    except BrokenPipeError:
        print(f"[!] 连接已断开，无法发送响应到 {addr[0]}:{addr[1]}")
    except ConnectionResetError:
        print(f"[!] 连接被客户端 {addr[0]}:{addr[1]} 重置，无法发送响应")
    except socket.timeout:
        print(f"[!] 发送响应到 {addr[0]}:{addr[1]} 超时")
    except Exception as e:
        print(f"[!] 发送响应数据包时出错: {e}")

# 在 load_smap_file 函数中添加文件大小检查
def load_smap_file(map_name):
    import os
    import glob

    # 查找当前目录或指定目录下的.smap文件
    # 这里假设.smap文件在当前工作目录下
    smap_filename = f"{map_name}.smap"

    # 如果直接找不到，尝试模糊匹配
    if not os.path.exists(smap_filename):
        # 尝试在可能的目录中查找
        matches = glob.glob(f"**/{smap_filename}", recursive=True)
        if matches:
            smap_filename = matches[0]
        else:
            # 如果还是找不到，尝试匹配部分名称
            matches = glob.glob(f"**/*{map_name}*.smap", recursive=True)
            if matches:
                smap_filename = matches[0]
            else:
                return None

    # 检查文件大小
    try:
        file_size = os.path.getsize(smap_filename)
        if file_size > 10 * 1024 * 1024:  # 如果文件大于10MB
            print(f"[!] 警告: 文件 {smap_filename} 大小为 {file_size / (1024*1024):.2f}MB，可能影响性能")
    except OSError:
        pass  # 如果无法获取文件大小，继续处理

    try:
        with open(smap_filename, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"[!] 读取文件 {smap_filename} 失败: {e}")
        return None

# 启动TCP服务器监听指定端口
def start_server(port):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        server.bind(('0.0.0.0', port))
        #server.bind(('127.0.0.1', port))
        server.listen(5)
        print(f"[*] 正在监听端口 {port}")
        while True:
            try:
                conn, addr = server.accept()
                # 创建线程处理客户端连接
                client_thread = threading.Thread(target=handle_client, args=(conn, addr, port))
                client_thread.daemon = True  # 设置为守护线程
                client_thread.start()
            except Exception as e:
                print(f"[!] 接受连接时发生错误: {e}")
                continue
    except Exception as e:
        print(f"[!] 端口 {port} 启动失败: {e}")
    finally:
        try:
            server.close()
            print(f"[*] 端口 {port} 服务器已关闭")
        except Exception as e:
            print(f"[!] 关闭服务器时发生错误: {e}")

# 要监听的端口列表
ports = [19204, 19205, 19206, 19207, 19210, 19303]

# 为每个端口启动一个监听线程
threads = []
for port in ports:
    thread = threading.Thread(target=start_server, args=(port,))
    thread.daemon = True  # 设置为守护线程，主线程退出时自动结束
    thread.start()
    threads.append(thread)

# 主线程保持运行
try:
    for thread in threads:
        thread.join()
except KeyboardInterrupt:
    print("\n[.] 程序终止，关闭所有监听端口。")